<?php

class BPATemplate{

    public static function generateBPAMetodologyMetabox($post){
        wp_nonce_field( 'bpa_meta_box', 'bpa_meta_box_nonce' );
        $metodology = get_post_meta( $post->ID, '_bpa_metodology', true );
        $settings = array( '_bpa_metodology' => false );
        wp_editor($metodology, '_bpa_metodology' ,$settings);
    }

    public static function generateBPAAmountMetabox($post){
        $amount = get_post_meta( $post->ID, '_bpa_amount', true );
        $settings = array( '_bpa_amount' => false );
        wp_editor($amount, '_bpa_amount' ,$settings);
    }
    
    public static function generateBPAReturnsMetabox($post){
        $returns = get_post_meta( $post->ID, '_bpa_returns', true );
        $settings = array( '_bpa_returns' => false );
        wp_editor($returns, '_bpa_returns' ,$settings);
    }
    
    public static function generateBPAProvidersMetabox($post){
        $providers_list = get_post_meta( $post->ID, '_bpa_providers', true );
        $providers = get_posts(array('posts_per_page'=> 99,'post_type' => 'provider','order' => 'ASC','orderby' => 'title'));     
        for($i=0;$i<count($providers);$i++){
            $checked = "";    
            if($providers_list!='' && in_array($providers[$i]->ID,$providers_list)){
                $checked = " checked='checked' ";
            }
            echo '<input '. $checked .'type="checkbox" name="_bpa_providers[]" value="'.$providers[$i]->ID.'">'.$providers[$i]->post_title.'</option>';
            echo "<br/>";
        }
    }
    
    public static function generateBPASavingsMetabox($post){
        
        $savings = get_post_meta( $post->ID, '_bpa_savings', true );
       
?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('.metabox_submit').click(function(e) {
                    e.preventDefault();
                    $('#publish').click();
                });
                $('#add-row').on('click', function() {
                    var row = $('.empty-row.screen-reader-text').clone(true);
                    row.removeClass('empty-row screen-reader-text');
                    row.insertBefore('#repeatable-fieldset-one tbody>tr:last');
                    return false;
                });
                $('.remove-row').on('click', function() {
                    $(this).parents('tr').remove();
                    return false;
                });

                $('#repeatable-fieldset-one tbody').sortable({
                    opacity: 0.6,
                    revert: true,
                    cursor: 'move',
                    handle: '.sort'
                });
            });
        </script>
         
        <table id="repeatable-fieldset-one" width="100%">
            <thead>
                <tr>
                    <th width="2%"></th>
                    <th width="30%">Nombre</th>
                    <th width="60%">Valor</th>
                    <th width="2%"></th>
                </tr>
            </thead>
            <tbody>
            <?php
                if ( $savings ) :
                    foreach ( $savings as $field ) {
            ?>
                    <tr>
                        <td><a class="button remove-row" href="#">-</a></td>
                        <td><input type="text" class="widefat" name="name[]" value="<?php if($field['name'] != '') echo esc_attr( $field['name'] ); ?>" /></td>
                        <td><input type="text" class="widefat" name="value[]" value="<?php if ($field['value'] != '') echo esc_attr( $field['value'] ); else echo ''; ?>" /></td>
                        <td><a class="sort">|||</a></td>
                    </tr>
            <?php
                    }
                else :
                    // show a blank one
        ?>
                    <tr>
                        <td><a class="button remove-row" href="#">-</a></td>
                        <td><input type="text" class="widefat" name="name[]" /></td>
                        <td><input type="text" class="widefat" name="value[]" value="" /></td>
                        <td><a class="sort">|||</a></td>
                    </tr>
            <?php endif; ?>
         
                <!-- empty hidden one for jQuery -->
                <tr class="empty-row screen-reader-text">
                    <td><a class="button remove-row" href="#">-</a></td>
                    <td><input type="text" class="widefat" name="name[]" /></td>
                    <td><input type="text" class="widefat" name="value[]" value="" /></td>
                    <td><a class="sort">|||</a></td>
                </tr>
            </tbody>
        </table>
         
        <p>
            <a id="add-row" class="button" href="#">Agregar uno nuevo</a>
            <input type="submit" class="metabox_submit" value="Guardar" />
        </p>
    
<?php
        
    }

    public static function saveBPAMetabox($post_id){
        
        global $wpdb;
        
        if ( ! isset( $_POST['bpa_meta_box_nonce'] ) ) {
            return;
        }
        if ( ! wp_verify_nonce( $_POST['bpa_meta_box_nonce'], 'bpa_meta_box' ) ) {
            return;
        }

        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        //TODO: Should check capabilities
        /*if ( isset( $_POST['slide'] ) && 'page' == $_POST['post_type'] ) {
            if ( ! current_user_can( 'edit_slide', $post_id ) ) {
                return;
            }
        } */
        if ( ! isset( $_POST['_bpa_metodology'] ) ) {
            return;
        }
        
        $modify_water = $_POST['modify_energy'];
        $modify_energy = $_POST['modify_energy'];
        
        if($modify_water != 0 && $modify_energy != 0){
            
            $delete_query = "DELETE FROM bpa_saving_basic_device WHERE post_id=%d";
            $wpdb->query($wpdb->prepare($delete_query, $post_id));

            /// Saving water

            //Basic device insertion
            $water_basic_device_counter = $_POST['water_basic_device_counter'];
            $water_basic_device_count = count($water_basic_device_counter);

            $water_basic_device_id = $_POST['water_basic_device'];
            $water_basic_device_description = $_POST['water_basic_device_description'];
            $water_basic_device_usage = $_POST['water_basic_device_usage'];
            $water_basic_device_consumption = $_POST['water_basic_device_consumption'];

            $water_saving_device = $_POST['water_saving_device_array'];

            for ( $i = 0; $i < $water_basic_device_count; $i++ ) {

                $device_counter = $water_basic_device_counter[$i];
                if($device_counter == 0){
                    continue;
                }

                $device_id = $water_basic_device_id[$i];
                $device_description = $water_basic_device_description[$i];
                $device_usage = $water_basic_device_usage[$i];
                $device_consumption = $water_basic_device_consumption[$i];

                if($device_id == 0){
                    continue;
                }

                $insert_query = "INSERT INTO bpa_saving_basic_device(post_id, item_id, description, average_use, consumption_per_time) 
                                VALUES (%d, %d, %s, %d, %f)";
                $wpdb->query($wpdb->prepare($insert_query, $post_id, $device_id, $device_description, $device_usage, $device_consumption));
                $basic_device_id = $wpdb->insert_id;

                //Saving device insertions
                $saving_devices_string = $water_saving_device[$i];
                $saving_devices = explode("/", $saving_devices_string);

                $saving_devices_count = count($saving_devices);

                for ( $j = 0; $j < $saving_devices_count; $j++ ) {

                    $saving_device = explode("+", $saving_devices[$j]);
                    $saving_device_id = $saving_device[0];
                    $saving_device_ratio = $saving_device[1];

                    if ( $saving_device != null && $saving_device_id != 0 ) {
                        $insert_query = "INSERT INTO bpa_saving_alternative_device (basic_device_id, saver_item_id, saving_ratio) 
                                            VALUES (%d, %d, %f);";
                        $wpdb->query($wpdb->prepare($insert_query, $basic_device_id, $saving_device_id, $saving_device_ratio));

                    } 
                }

            }


            /// Saving energy

            $energy_basic_device_counter = $_POST['energy_basic_device_counter'];
            $energy_basic_device_count = count($energy_basic_device_counter);

            $energy_basic_device_id  = $_POST['energy_basic_device'];
            $energy_basic_device_description = $_POST['energy_basic_device_description'];
            $energy_basic_device_usage = $_POST['energy_basic_device_usage'];
            $energy_basic_device_consumption = $_POST['energy_basic_device_consumption'];

            $energy_saving_device = $_POST['energy_saving_device_array'];

            for ( $i = 0; $i < $energy_basic_device_count; $i++ ) {

                $device_counter = $energy_basic_device_counter[$i];
                if($device_counter == 0){
                    continue;
                }

                $device_id = $energy_basic_device_id[$i];
                $device_description = $energy_basic_device_description[$i];
                $device_usage = $energy_basic_device_usage[$i];
                $device_consumption = $energy_basic_device_consumption[$i];

                if($device_id == 0){
                    continue;
                }

                $insert_query = "INSERT INTO bpa_saving_basic_device(post_id, item_id, description, average_use, consumption_per_time) 
                                VALUES (%d, %d, %s, %d, %f)";
                $wpdb->query($wpdb->prepare($insert_query, $post_id, $device_id, $device_description, $device_usage, $device_consumption));
                $basic_device_id = $wpdb->insert_id;

                //Saving device insertions
                $saving_devices_string = $energy_saving_device[$i];
                $saving_devices = explode("/", $saving_devices_string);

                $saving_devices_count = count($saving_devices);

                for ( $j = 0; $j < $saving_devices_count; $j++ ) {

                    $saving_device = explode("+", $saving_devices[$j]);
                    $saving_device_id = $saving_device[0];
                    $saving_device_ratio = $saving_device[1];

                    if ( $saving_device != null && $saving_device_id != 0 ) {
                        $insert_query = "INSERT INTO bpa_saving_alternative_device (basic_device_id, saver_item_id, saving_ratio) 
                                            VALUES (%d, %d, %f);";
                        $wpdb->query($wpdb->prepare($insert_query, $basic_device_id, $saving_device_id, $saving_device_ratio));

                    } 
                }

            }
        }
       
        $bpa_metodology  =  $_POST['_bpa_metodology'] ;
        $bpa_amount =  $_POST['_bpa_amount'] ;
        $bpa_returns = $_POST['_bpa_returns'] ;
        $bpa_providers = $_POST['_bpa_providers'] ;
  

        //Savings
        $old = get_post_meta($post_id, '_bpa_savings', true);
        $new = array();
     
     
        $names = $_POST['name'];
        $urls = $_POST['value'];
     
        $count = count( $names );
     
        for ( $i = 0; $i < $count; $i++ ) {
            if ( $names[$i] != '' ) {
                $new[$i]['name'] = stripslashes( strip_tags( $names[$i] ) );
                $new[$i]['value'] = stripslashes( $urls[$i] );
            } 
        }
            
        if ( !empty( $new ) && $new != $old )
            update_post_meta( $post_id, '_bpa_savings', $new );
        elseif ( empty($new) && $old )
            delete_post_meta( $post_id, '_bpa_savings', $old );

        update_post_meta( $post_id, '_bpa_metodology', $bpa_metodology );
        update_post_meta( $post_id, '_bpa_amount', $bpa_amount);
        update_post_meta( $post_id, '_bpa_returns', $bpa_returns );   
        update_post_meta( $post_id, '_bpa_providers', $bpa_providers );
       
    }


    public static function generateBPAWaterMetabox($post){
        include get_template_directory() . "/templates/bpa_template_water_metabox.php";
    }

    public static function generateBPAEnergyMetabox($post){
        include get_template_directory() . "/templates/bpa_template_energy_metabox.php";
    }
}
